﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using Gollie.DataTables;
using Gollie.Payment.Targetpay;
using Gollie.Mail;

namespace Gollie.Controls
{
	public partial class BankWirePayment : AuthenticationRequiredCustomerBaseUserControl
	{
		private static string bankWireReportHandler = ConfigAppSettings.GetValue("bankwirereporthandler");
		private static string bankWireReturnHandler = null;

		protected override void OnFirstHit(object sender, EventArgs e)
		{
			return; //no bankwire possibility yet...

			this.Populate();
		}

		protected override void Render(HtmlTextWriter writer)
		{
			//no bankwire possibility yet...
			return;
		}

		private void Populate()
		{
			decimal totPrice;
			decimal totCredit;
			this.OrderBasketData.Sum(out totCredit, out totPrice);

			this.lblAmount.Text = ObjectFormatter.GetCurrencyString(totPrice);
			int amount10 = (int)(totPrice * 100);

			BankWire bankWire = new BankWire("57429", this.UserInfo.Gebruikersnaam + ", Gollie", amount10, bankWireReportHandler, bankWireReturnHandler);

			if (bankWire.Error == false)
			{
				this.lblKenmerk.Text = bankWire.Kenmerk;
				this.lblRknr.Text = bankWire.IbanRknr;
				this.lblTenaamstelling.Text = bankWire.TenaamStelling;

				try
				{
					Database.Queries.InsertDeposit(bankWire.Kenmerk, this.UserInfo.Id, totPrice, 0, this.OrderBasketData);

					Session.Remove("orderbasket");

					this.SendPaymentInfoMail(bankWire, totPrice);

					if (Convert.ToBoolean(ConfigAppSettings.GetValue("simulatepayment")))
					{
						string r = WebReader.ReadUrl(bankWireReportHandler + "?trxid=" + Uri.EscapeDataString(bankWire.Kenmerk) + "&rtlo=57429&amountdue=" + amount10.ToString() + "&amountpaid=" + amount10.ToString());
					}
				}
				catch (MySql.Data.MySqlClient.MySqlException ex)
				{
					this.Panel1.Visible = false;
					this.ErrorPanel.Visible = true;
					this.lblErrorMsg.Text = MySqlErrorCodes.GetInstance().GetMessage(ex);
				}
			}
			else
			{
				this.Panel1.Visible = false;
				this.ErrorPanel.Visible = true;
				this.lblErrorMsg.Text = "De TargetMedia omgeving is op het moment onbereikbaar. Probeert u het later nog eens.";
			}

		}

		private void SendPaymentInfoMail(BankWire bankWire, decimal amount)
		{
			MailClient.Queue(new EMail
			{
				Name = "bankwirepaymentinfo",
				Recipients = this.UserInfo.Email,
				Args = new Dictionary<string, string>()
				{
											{ "{amount}", ObjectFormatter.GetCurrencyString(amount) },
											{ "{aanhef}", this.UserInfo.MailAanhef },
											{ "{kenmerk}", bankWire.Kenmerk },
											{ "{rknr}", bankWire.IbanRknr },
											{ "{tenaamstelling}", bankWire.TenaamStelling }
										    
				}
			});
		}
	}
}